/***************************************\
| Sets up left hand info bar and      	|
| maintains game timer.               	|
|					|
| Status: Timer only updates upon a	|
| key press.				|
\***************************************/

#include <sys/time.h>
#include <ctype.h>
#include <ncurses.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h> // not strings.h
#include <errno.h>

int     sec = 30;		// Starts timer at 30 seconds
WINDOW *timer_win;

// prints updated time to timer window
void disp_timer ( WINDOW *timer_win )
{
	mvwprintw(timer_win, 1, 3, "Time left:");
	mvwprintw(timer_win, 2, 3, "%02i seconds", sec);
	wrefresh(timer_win);
}

// Counts down to zero
void alarm_handler ( int sig )
{
	sec--;
	disp_timer(timer_win);
	if(sec == '0')
	{
		mvwprintw(timer_win, 2, 3, "Game over   ");
		sleep(3);
		exit;
	}
}

// Ending instructions
void finish(int sig)
{
  endwin();
  exit(0);
}


main( int argc, char *argv[])
{
	WINDOW *timer_win;
	char ch;
	struct itimerval value;

	initscr();
	cbreak();

	keypad(stdscr, TRUE);

	noecho();
	
	timer_win = newwin(getmaxy(stdscr), 22, 0, 0);
	
	refresh();
	wrefresh(timer_win);

	signal(SIGALRM, alarm_handler);			// Sets timer to update
	memset(&value, 0, sizeof(value));		// every second
	value.it_interval.tv_sec = 1;
	value.it_value.tv_sec    = 1;
	setitimer(ITIMER_REAL, &value, NULL); /* alarm reset after timer countdown */

	signal(SIGINT, finish); /* ^C exits and cleans up program */

	wclear(timer_win);
	disp_timer(timer_win);
	box(timer_win, 0, 0);
	mvwprintw(timer_win, 5, 3, "Difficulty: EASY");
	mvwprintw(timer_win, 8, 3, "Level: 1");
	mvwprintw(timer_win, 15, 3, "Ctrl+C to quit");
	wrefresh(timer_win);

	/* Refreshes timer_win every key press.
	/  Working on causing it to refresh every second.
	/*/
	while ((ch = wgetch(timer_win)) != ERR )
	{
		disp_timer(timer_win);
		wmove(timer_win, 2, 1);
		box(timer_win, 0, 0);
		mvwprintw(timer_win, 5, 3, "Difficulty: EASY");
		mvwprintw(timer_win, 8, 3, "Level: 1");
		mvwprintw(timer_win, 15, 3, "Ctrl+C to quit");
		wrefresh(timer_win);
	}

	endwin();
	return 0;
}
